/*
//  Copyright © 2014 Allen County Public Library.

  //        ACPL Mobile is free software: This program is distributed and you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.  ACPL Mobile is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, including without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with ACPL Mobile. If not, see http://www.gnu.org/licenses/.
 * Author: James Harpe
 * 
 * Description: Handles login procedure. If logged in, the user is forwarded to his desired activity. Otherwise, user
 * 				is forwarded to LoginActivity. This class also handles acquisition session tokens.
 */

package us.in.lib.acpl.Mobile_ACPL.ws;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import com.google.analytics.tracking.android.EasyTracker;

import us.in.lib.acpl.Mobile_ACPL.AccountActivity;
import us.in.lib.acpl.Mobile_ACPL.OverdriveActivity;
import us.in.lib.acpl.Mobile_ACPL.OverdriveActivity_;
import us.in.lib.acpl.Mobile_ACPL.R;
import us.in.lib.acpl.Mobile_ACPL.SettingsActivity;
import us.in.lib.acpl.Mobile_ACPL.context.Mobile_ACPL;
import us.in.lib.acpl.Mobile_ACPL.util.JSONArrayPrefs;
import us.in.lib.acpl.Mobile_ACPL.util.RestClient;
import us.in.lib.acpl.Mobile_ACPL.util.RestClient.RequestMethod;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Xml;
import android.view.Gravity;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

public class LoginHandler {

	public static final String LOGIN_URL = Mobile_ACPL.WS_HOST+"/symws/rest/security/loginUser";

	Activity act;
	Context context;
	String destination;
	SharedPreferences prefs;
	SharedPreferences.Editor editor;
	private boolean remember = false;

	public LoginHandler() {

	}

	public void handleLoginResult(boolean success) {
		if (!success) {
			editor.putString("user", null);
			editor.putString("pin", null);
			editor.putString("nickname", null);
			editor.putString("sessionKey", null);

			if (remember) {
				ArrayList<String> users = JSONArrayPrefs.getStringArrayPref(
						act, "savedUsers");
				ArrayList<String> pins = JSONArrayPrefs.getStringArrayPref(act,
						"savedPins");
				ArrayList<String> nicknames = JSONArrayPrefs
						.getStringArrayPref(act, "savedNicknames");
				ArrayList<String> remembers = JSONArrayPrefs
						.getStringArrayPref(act, "savedRemembers");
				users.remove(users.size() - 1);
				pins.remove(pins.size() - 1);
				nicknames.remove(nicknames.size() - 1);
				remembers.remove(remembers.size() - 1);
				JSONArrayPrefs.setStringArrayPref(act, "savedUsers", users);
				JSONArrayPrefs.setStringArrayPref(act, "savedPins", pins);
				JSONArrayPrefs.setStringArrayPref(act, "savedNicknames",
						nicknames);
				JSONArrayPrefs.setStringArrayPref(act, "savedRemembers",
						remembers);
			}

			editor.commit();

			Toast toast = Toast
					.makeText(
							act,
							"Login Error. Please check your card number and PIN and try again.",
							Toast.LENGTH_SHORT);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();

		} else {
			EasyTracker.getTracker().sendEvent("Login", "Login Success", null, null);
			
			editor.putBoolean("loggedIn", true);
			editor.commit();
			if (destination.equalsIgnoreCase("myAccount")) {
				Intent intent = new Intent(act, AccountActivity.class);
				act.startActivity(intent);
			}
			if(destination.equalsIgnoreCase("overdrive")){
				Intent intent = new Intent(act, OverdriveActivity_.class);
				act.startActivity(intent);
			}
			if (destination.equalsIgnoreCase("placeHold")) {
				act.setResult(Activity.RESULT_OK);
				act.finish();
			}
			if (destination.equalsIgnoreCase("displayBarcode")) {
				String data = prefs.getString("user", null);
				data = "A" + data + "T";

				Intent intent = new Intent(
						"com.google.zxing.client.android.ENCODE");

				intent.putExtra("ENCODE_FORMAT", "CODABAR");

				intent.putExtra("ENCODE_DATA", data);
				act.startActivity(intent);
			}

			if (destination.equalsIgnoreCase("settings")) {
				Intent intent = new Intent(act, SettingsActivity.class);
				act.startActivity(intent);
			}
			if (destination.equalsIgnoreCase("event")) {
				act.setResult(Activity.RESULT_OK);
				act.finish();

			}
		}
	}

	public void handleLoginButtonPress(Activity act, String[] params,
			String destination, boolean remember) {
		this.remember = remember;
		this.act = act;
		this.destination = destination;
		this.prefs = act.getSharedPreferences("myPrefs",
				Context.MODE_WORLD_WRITEABLE);
		this.editor = prefs.edit();

		new LoginTask().execute(params);
	}

	public void getNewSessionToken(SharedPreferences prefs, Context context) {
		this.context = context;
		this.prefs = prefs;
		this.editor = prefs.edit();
		GetNewSessionTokenTask obj = new GetNewSessionTokenTask();
		obj.execute();
		synchronized (obj) {
			try {
				obj.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}

	private class GetNewSessionTokenTask extends AsyncTask<Void, Void, String> {

		@Override
		protected String doInBackground(Void... params) {
			String user = prefs.getString("user", null);
			String pin = prefs.getString("pin", null);

			RestClient client = new RestClient(LOGIN_URL);
			client.AddHeader("x-sirs-clientID", SearchCatalogHandler.CLIENT_ID);
			client.AddParam("login", user);
			client.AddParam("password", pin);

			try {
				client.Execute(RequestMethod.POST);
			} catch (Exception e) {

			}

			String response = client.getResponse();

			if (response == null) {

				editor.putString("sessionToken", null);
				editor.commit();
				synchronized (this) {
					this.notify();
				}
				return null;
			}
			XmlPullParser parser = Xml.newPullParser();

			String sessionToken = null;
			try {

				parser.setInput(new StringReader(response));
				int eventType = parser.next();

				while (eventType != XmlPullParser.END_DOCUMENT) {
					if (eventType == XmlPullParser.START_TAG) {
						String name = parser.getName();
						if (name.equalsIgnoreCase("sessionToken")) {
							sessionToken = parser.nextText();
							break;
						}
					}
					eventType = parser.next();
				}

				editor.putString("sessionToken", sessionToken);
				editor.commit();

				synchronized (this) {
					this.notify();
				}

			} catch (XmlPullParserException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return sessionToken;
		}

		@Override
		protected void onPostExecute(String sessionToken) {
			if (sessionToken == null) {

				Toast toast = Toast.makeText(context, "Connection error",
						Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
			}
		}

	}

	private class LoginTask extends AsyncTask<String, Void, Boolean> {

		
		private ProgressDialog progDialog;
		@Override
		protected void onPreExecute(){
			
			progDialog = ProgressDialog.show(act, "Logging In", "Please wait....", true);
		
		}
		@Override
		protected Boolean doInBackground(String... params) {
			String user = params[0];
			String pin = params[1];

			RestClient client = new RestClient(LOGIN_URL);
			client.AddHeader("x-sirs-clientID", SearchCatalogHandler.CLIENT_ID);
			client.AddParam("login", user);
			client.AddParam("password", pin);

			try {
				client.Execute(RequestMethod.POST);
			} catch (Exception e) {
				e.printStackTrace();
			}

			String response = client.getResponse();

			if (response == null) {
				return false;
			}
			XmlPullParser parser = Xml.newPullParser();

			String sessionToken = null;
			try {

				parser.setInput(new StringReader(response));
				int eventType = parser.next();

				while (eventType != XmlPullParser.END_DOCUMENT) {
					if (eventType == XmlPullParser.START_TAG) {
						String name = parser.getName();
						if (name.equalsIgnoreCase("sessionToken")) {
							sessionToken = parser.nextText();
							break;
						}
					}
					eventType = parser.next();
				}

				editor.putString("sessionToken", sessionToken);
				editor.commit();

				if (sessionToken == null) {
					return false;
				} else {
					return true;
				}
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Boolean bool) {
			progDialog.dismiss();
			handleLoginResult(bool.booleanValue());
		}
	}
}
